Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

A light stack implementation for Win32

0.00/5 (No votes)
18 Mar 2004 2  
A simple and very small stack implementation for any type.

Introduction

This is a small stack implementation that is relied on MFC CArray template class. It has implemented the three mostly needed stack functions Push, Pop and Peek. The class is directly derived from CArray and consequently it supplies all inherited functions too.

Usage sample

CStack<int> m_stack;
m_stack.Push( 1973 );
m_stack.Push( 2004 );
m_stack.Push( 30 ); 
int size = m_stack.GetSize();// an inherited CArray function. 

int value = m_stack.Peek(); // only returns the last inserted value 

int value = m_stack.Pop(); // returns the last inserted value

                          // and removes it from stack.

The implementation

// Copyright (C) 2003 by Daniel Junges 

// http://junges.gmxhome.de/

// Written by Daniel Junges daniel-junges@gmx.net

// All rights reserved

//

// This is free software.

// This code may be used in compiled form in any way you desire. :-)

//

// Release Date and Version:

// Version: 1.0 Mars 2003

//////////////////////////////////////////////////////////////////////

// 


#ifndef _H_TEMPLATE_H_
#define _H_TEMPLATE_H_


template <class T> class CStack : public CArray<T,T>
{
public:
 // Add element to top of stack

 void Push( T newView ){ 
  Add( newView );
 }
 // Peek at top element of stack

 T Peek(int index=-1){ 
  return ( index >= GetSize() || 
    GetSize()==0) ? NULL : ElementAt( ( index==-1?GetSize()-1:index) ); 
 }
 // Pop top element off stack

 T Pop(){ 
  T item = Peek();
  if(item) RemoveAt(GetSize()-1);
  return item; 
 }
};


#endif

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here